package com.xiaoshuidi.cloud.module.member.repository;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xiaoshuidi.cloud.framework.web.core.util.WebFrameworkUtils;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.BookingCouponSendVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.CancelBookingCouponSendVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.NewSignCouponSendVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.coupon.vo.OldBringNewCouponSendVO;
import com.xiaoshuidi.cloud.module.member.controller.app.coupon.vo.CouponCustomerValidQueryVo;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponSendMethodEnum;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponTypeEnum;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponUsageStatusEnum;
import com.xiaoshuidi.cloud.module.member.enums.coupon.CouponUsegeTimeTypeEnum;
import com.xiaoshuidi.cloud.module.member.mapper.coupon.CouponCustomerMapper;
import com.xiaoshuidi.cloud.module.member.pojo.coupon.CouponCustomerEntity;
import com.xiaoshuidi.cloud.module.member.pojo.coupon.CouponEntity;
import com.xiaoshuidi.cloud.module.member.pojo.coupon.CouponRecordEntity;
import com.xiaoshuidi.cloud.module.member.pojo.user.MemberUser;
import com.xiaoshuidi.cloud.module.member.util.CodeUtil;
import com.xiaoshuidi.cloud.module.member.utils.DateUtils;
import com.xiaoshuidi.cloud.module.system.api.user.AdminUserApi;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class MemberCouponCustomerRepository extends ServiceImpl<CouponCustomerMapper, CouponCustomerEntity> {
    private final CouponCustomerMapper mapper;

    private final CodeUtil codeUtil;
    private final AdminUserApi adminUserApi;

    public void sendBookingCoupon(BookingCouponSendVO bookingCouponSendVO, CouponEntity coupon, MemberUser user, CouponRecordEntity couponRecordEntity) {
        String key = CouponTypeEnum.RESERVATION_DISCOUNT.getCode() + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String sequencecode = codeUtil.queryMaxCouponCode(key);
        Date expirationStartTime = new Date();
        //设置优惠码
        CouponCustomerEntity couponCustomerEntity = new CouponCustomerEntity()
                .setUserId(user.getId()).setUserName(user.getNickname())
                .setUserPhone(user.getMobile()).setCouponId(coupon.getId())
                .setRecordId(couponRecordEntity.getId()).setBusinessKey(bookingCouponSendVO.getBusinessKey())
                .setCouponCode(key + sequencecode)
                .setUsageStatus(CouponUsageStatusEnum.TO_BE_USED.getCode())
                //优惠金额 或者百分比
                .setPreferentialAmount(coupon.getMarginPreference())
                //预定优惠使用日期只有发券后多少天内有效
                .setExpirationStartTime(expirationStartTime)
                .setExpirationEndTime(DateUtils.addDateDays(expirationStartTime, coupon.getCouponUsageTime()))
                .setIssuingMethod(CouponSendMethodEnum.AUTOMATIC.getCode())
                .setRemarks(couponRecordEntity.getRemarks())
                .setIsLocked(false).setPreferentialContentType(coupon.getPreferentialContentType());
        couponCustomerEntity.setTenantId(bookingCouponSendVO.getTenantId());
        mapper.insert(couponCustomerEntity);
    }

    public List<CouponCustomerEntity> cancelBookingCoupon(CancelBookingCouponSendVO reserveCancelMessage) {
        LambdaQueryWrapperX<CouponCustomerEntity> wrapperX = new LambdaQueryWrapperX<CouponCustomerEntity>()
                .eqIfPresent(CouponCustomerEntity::getBusinessKey, reserveCancelMessage.getBusinessKey())
                .eqIfPresent(CouponCustomerEntity::getUserId, reserveCancelMessage.getUserId())
                .eqIfPresent(CouponCustomerEntity::getTenantId, reserveCancelMessage.getTenantId());
        List<CouponCustomerEntity> list = mapper.selectList(wrapperX);
        return list;
    }

    public void sendOldBringsNewCoupon(OldBringNewCouponSendVO oldBringNewCouponSendVO, CouponEntity coupon, MemberUser user, CouponRecordEntity couponRecordEntity, String flag) {

        String key = CouponTypeEnum.OLD_WITH_NEW_DISCOUNT.getCode() + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String sequencecode = codeUtil.queryMaxCouponCode(key);
        Date expirationStartTime = new Date();
        //设置优惠码
        CouponCustomerEntity couponCustomerEntity = new CouponCustomerEntity()
                .setUserId(user.getId()).setUserName(user.getNickname())
                .setUserPhone(user.getMobile()).setCouponId(coupon.getId())
                .setRecordId(couponRecordEntity.getId()).setBusinessKey(oldBringNewCouponSendVO.getBusinessKey())
                .setCouponCode(key + sequencecode)
                .setUsageStatus(CouponUsageStatusEnum.TO_BE_USED.getCode())
                //预定优惠使用日期只有发券后多少天内有效
                .setExpirationStartTime(expirationStartTime)
                .setExpirationEndTime(DateUtils.addDateDays(expirationStartTime, coupon.getCouponUsageTime()))
                .setIssuingMethod(CouponSendMethodEnum.AUTOMATIC.getCode())
                .setRemarks(couponRecordEntity.getRemarks())
                .setIsLocked(false);
        couponCustomerEntity.setTenantId(oldBringNewCouponSendVO.getTenantId());

        if (flag.equals("new")) {
            //优惠金额 或者百分比
            couponCustomerEntity.setPreferentialAmount(coupon.getMarginPreference())
                    .setPreferentialContentType(coupon.getPreferentialContentType());
        } else if (flag.equals("old")) {
            //优惠金额 或者百分比
            couponCustomerEntity.setPreferentialAmount(coupon.getMarginPreferenceOld())
                    .setPreferentialContentType(coupon.getPreferentialContentTypeOld());
        }
        mapper.insert(couponCustomerEntity);

    }

    public void sendNewSignCoupon(NewSignCouponSendVO newSignCouponSendVO, CouponEntity coupon, MemberUser user, CouponRecordEntity couponRecordEntity, int num) {
        for (int i = 0; i < num; i++) {
            String key = CouponTypeEnum.NEW_SIGNING_DISCOUNT.getCode() + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String sequencecode = codeUtil.queryMaxCouponCode(key);
            Date expirationStartTime = new Date();
            //设置优惠码
            CouponCustomerEntity couponCustomerEntity = new CouponCustomerEntity()
                    .setUserId(user.getId()).setUserName(user.getNickname())
                    .setUserPhone(user.getMobile()).setCouponId(coupon.getId())
                    .setRecordId(couponRecordEntity.getId()).setBusinessKey(newSignCouponSendVO.getBusinessKey())
                    .setCouponCode(key + sequencecode)
                    .setUsageStatus(CouponUsageStatusEnum.TO_BE_USED.getCode())
                    //优惠金额 或者百分比
                    .setPreferentialAmount(coupon.getMarginPreference())
                    //预定优惠使用日期只有发券后多少天内有效
                    .setExpirationStartTime(expirationStartTime)
                    .setIssuingMethod(CouponSendMethodEnum.AUTOMATIC.getCode())
                    .setRemarks(couponRecordEntity.getRemarks())
                    .setIsLocked(false).setPreferentialContentType(coupon.getPreferentialContentType());
            couponCustomerEntity.setTenantId(newSignCouponSendVO.getTenantId());
            if (CouponUsegeTimeTypeEnum.CONTRACT_PERIOD_VALID.getCode().equals(coupon.getCouponUsageTimeType().toString())) {
                couponCustomerEntity.setExpirationEndTime(newSignCouponSendVO.getEndTime());
            } else if (CouponUsegeTimeTypeEnum.DAYS_VALID.getCode().equals(coupon.getCouponUsageTimeType().toString())) {
                couponCustomerEntity.setExpirationEndTime(DateUtils.addDateDays(expirationStartTime, coupon.getCouponUsageTime()));
            }

            mapper.insert(couponCustomerEntity);
        }
    }

    public int getOldBringsNewNum(OldBringNewCouponSendVO oldBringNewCouponSendVO, String flag, Long couponId) {
        LambdaQueryWrapperX<CouponCustomerEntity> wrapperX = new LambdaQueryWrapperX<CouponCustomerEntity>()
                .eqIfPresent(CouponCustomerEntity::getCouponId, couponId)
                .eqIfPresent(CouponCustomerEntity::getTenantId, oldBringNewCouponSendVO.getTenantId());
        if (flag.equals("new")) {
            wrapperX.eqIfPresent(CouponCustomerEntity::getUserId, oldBringNewCouponSendVO.getNewUserId());
        } else if (flag.equals("old")) {
            wrapperX.eqIfPresent(CouponCustomerEntity::getUserId, oldBringNewCouponSendVO.getOldUserId());
        }

        return mapper.selectCount(wrapperX).intValue();
    }

    public List<CouponCustomerValidQueryVo> getCouponCustomerCoupons(Long tenantUserId) {
        return mapper.getCouponCustomerCoupons(tenantUserId);
    }

    public List<CouponCustomerValidQueryVo> getCouponCustomerCouponsByIds(List<Long> ids) {
        return mapper.getCouponCustomerCouponsByIds(ids);
    }

    public void sendManualCouponCoupon(CouponEntity coupon, MemberUser user, CouponRecordEntity couponRecordEntity) {
        int num = couponRecordEntity.getIssuerNum().intValue();
        for (int i = 0; i < num; i++) {
            String key = "";
            if (coupon.getCouponType().intValue() == CouponTypeEnum.OTHER_DISCOUNT.getNum().intValue()) {
                key = CouponTypeEnum.OTHER_DISCOUNT.getCode() + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            } else if (coupon.getCouponType().intValue() == CouponTypeEnum.INTERNAL_EMPLOYEE_DISCOUNT.getNum().intValue()) {
                key = CouponTypeEnum.INTERNAL_EMPLOYEE_DISCOUNT.getCode() + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            }

            String sequencecode = codeUtil.queryMaxCouponCode(key);
            //设置优惠码
            CouponCustomerEntity couponCustomerEntity = new CouponCustomerEntity()
                    .setUserId(user.getId()).setUserName(user.getNickname())
                    .setUserPhone(user.getMobile()).setCouponId(coupon.getId())
                    .setRecordId(couponRecordEntity.getId())
                    .setCouponCode(key + sequencecode)
                    .setUsageStatus(CouponUsageStatusEnum.TO_BE_USED.getCode())
                    .setPreferentialContentType(coupon.getPreferentialContentType())
                    //优惠金额 或者百分比
                    .setPreferentialAmount(coupon.getMarginPreference())
                    .setIssuingMethod(CouponSendMethodEnum.MANUAL.getCode())
                    .setRemarks(couponRecordEntity.getRemarks())
                    .setIsLocked(false);
            try {
                String nickname = adminUserApi.getUser(WebFrameworkUtils.getLoginUserId()).getData().getNickname();
                couponCustomerEntity.setIssuerName(nickname);
            } catch (Exception e) {
                log.error("获取用户名失败");
            }

            /**
             * 使用类型 1合同期类有效 2 发券后多少天 3 固定日期
             */
            if (CouponUsegeTimeTypeEnum.DAYS_VALID.getCode().equals(coupon.getCouponUsageTimeType().toString())) {
                couponCustomerEntity.setExpirationStartTime(new Date());
                couponCustomerEntity.setExpirationEndTime(DateUtils.addDateDays(couponCustomerEntity.getExpirationStartTime(), coupon.getCouponUsageTime()));
            } else if (CouponUsegeTimeTypeEnum.FIXED_DATE_VALID.getCode().equals(coupon.getCouponUsageTimeType().toString())) {
                couponCustomerEntity.setExpirationStartTime(coupon.getExpirationStartTime());
                couponCustomerEntity.setExpirationEndTime(coupon.getExpirationEndTime());
            }
            mapper.insert(couponCustomerEntity);
        }
    }
}
